<template>
  <!-- 供应商/客户表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1373px"
    draggable
    :close-on-press-escape="false"
    @close="closeDialog"
  >
    <div class="app-container" style="padding: 0">
      <el-card shadow="never" class="table-container">
        <!-- 预留功能 -->
        <!-- <template #header>
        <el-button type="success" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          :loading="deleteLoading"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template> -->
        <!-- 数据表格 -->
        <el-table
          :data="products"
          style="width: 100%"
          :key="Math.random"
          :header-cell-style="{ backgroundColor: '#F0F8FF' }"
          max-height="640px"
          border
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="90"
          />
          <el-table-column
            label="存货编码"
            header-align="center"
            align="left"
            prop="materialCode"
          />
          <el-table-column
            label="物料名称"
            header-align="center"
            align="left"
            prop="materialName"
          />
          <el-table-column
            label="规格"
            align="center"
            prop="materialSpecification"
          />
          <el-table-column
            label="数量单位"
            align="center"
            prop="quantityUnit"
          />
          <el-table-column label="物料类型" align="center" prop="materialType">
            <template #default="{ $index, row }">
              <el-tag>
                {{
                  dictionaryStore.filterDictName(
                    "MaterialType",
                    typeTrim(row.materialType)
                  )
                }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MDMPARTNERPRODUCTEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const products = ref([]);
const materials = ref([]);

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  materialId: [
    { required: true, message: "请选择物料", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  partnerId: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  materialSpecification: "",
  quantityUnit: "",
  materialType: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    products.value = props.data;
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formData.id = "";
  formData.partnerId = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.materialSpecification = "";
  formData.quantityUnit = "";
  formData.materialType = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 供应产品添加行 */
const handleProductAdd = () => {
  let sondata = JSON.parse(JSON.stringify(product));
  formData.products.push(sondata);
};

/** 供应产品删除行 */
const handleProductDelete = (index: any) => {
  formData.products.splice(index, 1);
};

/** 供应商/客户保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/mdm/mdmpartner/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getMaterials() {
  const data = await request({
    url: "/mdm/mdmmaterial/getListByUser",
    method: "get",
  });
  materials.value = data.data;
}

function materialChange(row: any) {
  const material = materials.value.find((item) => {
    return item.id === row.materialId;
  });
  row.materialSpecification = material.materialSpecification;
  row.quantityUnit = "个";
  row.materialType = material.materialType;
}

function typeTrim(val: String) {
  if (!val) {
    return "未设置";
  } else {
    return val;
  }
}

onMounted(() => {
  // getMaterials();
});

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
